package com.sfzd5.UI;

import com.google.gson.Gson;
import com.sfzd5.aiclassroom.modle.ExamQuestionsInfo;
import com.sfzd5.aiclassroom.modle.Question;
import org.apache.commons.io.FileUtils;

import javax.swing.*;
import javax.swing.table.AbstractTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class HomeWorkManager {
    List<ExamQuestionsInfo> examList;
    public JPanel mPanel;
    private JButton 删除Button;
    private JTable wTable;
    private JButton 课堂讲解Button;
    private JButton 编辑答题卡Button;
    private JButton 识别知识点Button;
    private JButton 导入button;
    private JButton 编辑button;
    private JButton 导出习题Button;
    WTableModel dataModel;

    public static File examDir = new File("exam");

    public HomeWorkManager() {

        课堂讲解Button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (wTable.getSelectedRowCount() > 0) {
                    int sRowId = wTable.getSelectedRow();
                    if (sRowId < 0)
                        return;
                    ExamQuestionsInfo task = examList.get(sRowId);
                    DataForm createHomeWorkPanel = new DataForm(task);
                    mPanel.removeAll();
                    mPanel.add(createHomeWorkPanel.mPanel, BorderLayout.CENTER);
                    mPanel.repaint();
                    mPanel.revalidate();
                    mPanel.updateUI();
                }
            }
        });

        删除Button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (wTable.getSelectedRowCount() > 0) {
                    int sRowId = wTable.getSelectedRow();
                    if (sRowId < 0)
                        return;
                    ExamQuestionsInfo task = examList.get(sRowId);
                    File taskFile = new File(examDir, task.id + ".json");
                    taskFile.delete();
                    examList.remove(task);
                    dataModel.fireTableDataChanged();
                }
            }
        });

        编辑答题卡Button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (wTable.getSelectedRowCount() > 0) {
                    int sRowId = wTable.getSelectedRow();
                    if (sRowId < 0)
                        return;
                    ExamQuestionsInfo task = examList.get(sRowId);
                    CreateAnswerSheetDialog createAnswerSheetDialog = new CreateAnswerSheetDialog(task);
                    createAnswerSheetDialog.setTitle("编辑答题卡");
                    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
                    int screenHeight = (int) screenSize.getHeight();
                    int screenWidth = (int) screenSize.getWidth();
                    Dimension d = new Dimension(screenWidth, screenHeight - 30);
                    createAnswerSheetDialog.setSize(d);
                    createAnswerSheetDialog.setPreferredSize(d);
                    createAnswerSheetDialog.setLocation(0, 0);
                    createAnswerSheetDialog.pack();
                    createAnswerSheetDialog.setVisible(true);
                }
            }
        });

        导入button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                ImportQuestionDialog importQuestionDialog = new ImportQuestionDialog();
                importQuestionDialog.setTitle("导入试题");
                Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
                int screenHeight = (int) screenSize.getHeight();
                int screenWidth = (int) screenSize.getWidth();
                Dimension d = new Dimension(screenWidth, screenHeight - 30);
                importQuestionDialog.setSize(d);
                importQuestionDialog.setPreferredSize(d);
                importQuestionDialog.pack();
                importQuestionDialog.setVisible(true);

                ExamQuestionsInfo info = importQuestionDialog.getExamQuestionsInfo();

                if (info != null) {
                    File taskFile = new File(examDir, info.id + ".json");
                    String json = new Gson().toJson(info);
                    try {
                        FileUtils.writeStringToFile(taskFile, json, "utf-8");
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }

                    int findi = -1;
                    for (int i = 0; i < examList.size(); i++) {
                        if (examList.get(i).id == info.id) {
                            findi = i;
                            break;
                        }
                    }
                    if (findi != -1) {
                        examList.remove(findi);
                    }
                    examList.add(info);
                    dataModel.fireTableDataChanged();
                }
            }
        });

        编辑button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (wTable.getSelectedRowCount() > 0) {
                    int sRowId = wTable.getSelectedRow();
                    if (sRowId < 0)
                        return;
                    ExamQuestionsInfo task = examList.get(sRowId);
                    EditExamQuestionsDialog dialog = new EditExamQuestionsDialog(task);
                    dialog.setTitle("编辑答案");
                    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
                    int screenHeight = (int) screenSize.getHeight();
                    int screenWidth = (int) screenSize.getWidth();
                    Dimension d = new Dimension(screenWidth, screenHeight - 30);
                    dialog.setSize(d);
                    dialog.setPreferredSize(d);
                    dialog.setLocation(0, 0);
                    dialog.pack();
                    dialog.setVisible(true);
                }
            }
        });

        识别知识点Button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (wTable.getSelectedRowCount() > 0) {
                    int sRowId = wTable.getSelectedRow();
                    if (sRowId < 0)
                        return;
                    ExamQuestionsInfo task = examList.get(sRowId);
                    PredictKnowledgeDialog dialog = new PredictKnowledgeDialog(task);
                    dialog.setTitle("识别习题知识点");
                    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
                    int screenHeight = (int) screenSize.getHeight();
                    int screenWidth = (int) screenSize.getWidth();
                    Dimension d = new Dimension(screenWidth, screenHeight - 30);
                    dialog.setSize(d);
                    dialog.setPreferredSize(d);
                    dialog.setLocation(0, 0);
                    dialog.pack();
                    dialog.setVisible(true);
                }
            }
        });

        if (!examDir.exists())
            examDir.mkdir();

        initData();
        导出习题Button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int sRowId = wTable.getSelectedRow();
                if (sRowId < 0)
                    return;
                ExamQuestionsInfo task = examList.get(sRowId);
                StringBuilder sb = new StringBuilder();
                sb.append("<html>\n");
                sb.append("<meta charset=\"utf-8\" />\n");
                sb.append("<title>").append(task.examName).append("</title>\n");
                sb.append("<body>\n");
                sb.append("<div>\n");
                for (String k : task.getSortedContentKeyList()) {
                    sb.append("<div>").append(k).append("</div>\n");
                    List<Question> qs = task.content.get(k);
                    sb.append("<ol>\n");
                    for (Question q : qs) {
                        sb.append("<li>").append(q.question_text).append("</li>\n");
                    }
                    sb.append("</ol>\n");
                }
                sb.append("</div>\n");
                sb.append("</html>\n</body>\n");
                File pdfFilePath = new File(HomeWorkManager.examDir, String.valueOf(task.id));
                File taskFile = new File(pdfFilePath, task.id + ".html");
                try {
                    FileUtils.writeStringToFile(taskFile, sb.toString(), "utf-8");
                    Desktop.getDesktop().open(taskFile);
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        });
    }

    void initData() {
        File[] examFiles = examDir.listFiles(new FilenameFilter() {
            @Override
            public boolean accept(File dir, String name) {
                return name.endsWith(".json");
            }
        });

        examList = new ArrayList<>();
        for (File f : examFiles) {
            try {
                String json = FileUtils.readFileToString(f, "utf-8");
                ExamQuestionsInfo info = new Gson().fromJson(json, ExamQuestionsInfo.class);
                examList.add(info);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        dataModel = new WTableModel();
        wTable.setModel(dataModel);
    }


    String[] columnNames = {"学科", "标题", "时间"};

    {
// GUI initializer generated by IntelliJ IDEA GUI Designer
// >>> IMPORTANT!! <<<
// DO NOT EDIT OR ADD ANY CODE HERE!
        $$$setupUI$$$();
    }

    /**
     * Method generated by IntelliJ IDEA GUI Designer
     * >>> IMPORTANT!! <<<
     * DO NOT edit this method OR call it in your code!
     *
     * @noinspection ALL
     */
    private void $$$setupUI$$$() {
        mPanel = new JPanel();
        mPanel.setLayout(new BorderLayout(0, 0));
        final JToolBar toolBar1 = new JToolBar();
        mPanel.add(toolBar1, BorderLayout.NORTH);
        导入button = new JButton();
        导入button.setText("导入");
        toolBar1.add(导入button);
        编辑button = new JButton();
        编辑button.setText("编辑答案");
        toolBar1.add(编辑button);
        删除Button = new JButton();
        删除Button.setText("删除");
        toolBar1.add(删除Button);
        课堂讲解Button = new JButton();
        课堂讲解Button.setText("课堂讲解");
        toolBar1.add(课堂讲解Button);
        编辑答题卡Button = new JButton();
        编辑答题卡Button.setText("编辑答题卡");
        toolBar1.add(编辑答题卡Button);
        识别知识点Button = new JButton();
        识别知识点Button.setText("识别知识点");
        toolBar1.add(识别知识点Button);
        导出习题Button = new JButton();
        导出习题Button.setText("导出习题");
        toolBar1.add(导出习题Button);
        final JPanel panel1 = new JPanel();
        panel1.setLayout(new BorderLayout(0, 0));
        mPanel.add(panel1, BorderLayout.CENTER);
        final JScrollPane scrollPane1 = new JScrollPane();
        panel1.add(scrollPane1, BorderLayout.CENTER);
        wTable = new JTable();
        scrollPane1.setViewportView(wTable);
    }

    /**
     * @noinspection ALL
     */
    public JComponent $$$getRootComponent$$$() {
        return mPanel;
    }

    class WTableModel extends AbstractTableModel {

        @Override
        public int getRowCount() {
            return examList.size();
        }

        @Override
        public int getColumnCount() {
            return columnNames.length;
        }

        @Override
        public Object getValueAt(int rowIndex, int columnIndex) {
            ExamQuestionsInfo task = examList.get(rowIndex);
            if (columnIndex == 0) {
                return task.subject;
            } else if (columnIndex == 1) {
                return task.examName;
            } else if (columnIndex == 2) {
                return task.creationTime.toLocalDateTime().toString();
            }
            return "";
        }

        @Override
        public String getColumnName(int column) {
            return columnNames[column];
        }
    }
}
